import { type TableColumnsType, type TableColumnType, Switch, Button, message, Tag, Popconfirm } from "ant-design-vue";
import { esArtPublishRuleApi } from "@/api/esArticle";
import { useDebounceFn } from "@vueuse/core";
import ruleStore from "@/stores/commonAsyncOptions";
import { OncePublishArticleButton } from "@/pages/home/esArticle/tsx/publishComponents";
import { toUrl } from "@/utils/common";
type OtherField = Record<keyof RuleStoreStateOptions, string>;
type TableDataItme = {
    id: number;
    rule_name: string;
    day_pub_num: number;
    custom_identifier: string;
    index: string;
} & OtherField &
    PostPublishRuleParams;

// 所有状态
const AllStatus: Record<string, Record<string, Ref<boolean>>> = reactive({});

// 创建tableColumn
export function useCreateTableColumns() {
    // 是否重新加载规则列表
    const isReloadRuleList: Ref<boolean> = ref(false);
    // 当前操作的规则名
    const ruleName = ref("");
    const isShowRuleName = ref(false);
    const columns: TableColumnsType = [
        {
            title: "id",
            width: 80,
            dataIndex: "id",
            key: "id",
            fixed: "left",
            align: "center"
        },
        {
            title: "规则名",
            width: 180,
            dataIndex: "rule_name",
            key: "rule_name",
            fixed: "left",
            align: "center",
            customRender(row) {
                return h(
                    "a",
                    {
                        onClick() {
                            isShowRuleName.value = true;
                            ruleName.value = row.value;
                        }
                    },
                    { default: () => row.value }
                );
            }
        },
        {
            title: "索引",
            dataIndex: "index_name",
            key: "index_name",
            width: 200,
            align: "center",
            fixed: "left",
            customRender: (row) =>
                h(
                    Button,
                    {
                        type: "link",
                        href: toUrl(`/esarticle/es-action?host=${row.record.es_search.host}&index=${row.value}`),
                        target: "_blank"
                    },
                    { default: () => row.value }
                )
        },
        {
            title: "规则类型",
            width: 100,
            dataIndex: "rule_type_name",
            key: "rule_type_name",
            align: "center"
        },
        {
            title: "自定义标识符",
            dataIndex: "custom_identifier_name",
            key: "custom_identifier_name",
            width: 120,
            align: "center"
        },
        {
            title: "发布类型",
            width: 200,
            dataIndex: "publish_type_name",
            key: "publish_type_name",
            align: "center"
        },
        {
            title: "创建人",
            dataIndex: "create_name",
            key: "create_name",
            width: 100,
            align: "center"
        },
        {
            title: "伪原创",
            dataIndex: "wyc_name",
            key: "wyc_name",
            width: 140,
            align: "center"
        },
        {
            title: "发布日选项",
            dataIndex: "week_option",
            key: "week_option",
            width: 100,
            align: "center",
            customRender:(r)=>r.value.length == 0 ? "每日都发" : r.value.join(",")
        },
        {
            title: "日发数",
            width: 80,
            dataIndex: "day_pub_num",
            key: "day_pub_num",
            align: "center",
            sorter: true
        },
        {
            title: "总数",
            width: 70,
            dataIndex: "article_sum",
            key: "article_sum",
            align: "center",
            sorter: true
        }
    ];
    const currentUpdatePublishRule = ref<null | PostPublishRuleParams>(null);
    const publishRuleComponentShow = ref(false);
    // 其他状态的开关 JSON数据的状态
    const otherStatusColumns = () => {
        const otherColumns: TableColumnsType = [
            {
                title: "标题替换",
                width:90,
                dataIndex: "title_replace"
            },
            {
                title: "内容替换",
                width:90,

                dataIndex: "content_replace"
            },
            {
                title: "标题插词",
                width:90,

                dataIndex: "title_insert_kwd"
            },
            {
                title: "头部插词",
                width:90,
                dataIndex: "head_insert_kwd"
            },
            {
                title: "中部插词",
                width:90,
                dataIndex: "center_insert_kwd"
            },
            {
                title: "底部插词",
                width:90,
                dataIndex: "footer_insert_kwd"
            },
            {
                title: "插入图片",
                width:90,
                dataIndex: "insert_img"
            },
            {
                title: "插入组合图片",
                width:120,
                dataIndex: "insert_zuhe_img"
            }
        ];
        // row.value 就是 dataIndex 对应的数据
        for (const column of otherColumns) {
            
            column["customRender"] = function (row) {
                // 如果规则状态没有开启 那么不用渲染开关了
                if (!row.record.status) {
                    // 这个状态是规则里面某些字段的状态
                    const status = row.value.status;
                    return h(Tag, { color: status ? "success" : "error" }, { default: () => (status ? "开启" : "关闭") });
                }
                return h(Switch, {
                    checkedChildren: "开启",
                    unCheckedChildren: "关闭",
                    checked: row.value.status,
                    onChange(checked: any) {
                        row.value.status = checked;
                    }
                });
            };
            column["align"] = "center";
        }
        return otherColumns;
    };
    // 规则状态
    const ruleStatusColumn: TableColumnType = {
        title: "规则状态",
        fixed: "right",
        align: "center",
        dataIndex: "status",
        width: 80,
        customRender(row: any) {
            const { id } = row.record;
            const status = toRef(row.record, "status");
            return h(Switch, {
                checkedChildren: "开启",
                unCheckedChildren: "关闭",
                checked: !!status.value,
                onChange(checked: any) {
                    status.value = checked ? 1 : 0;
                    updateDataCommonFunc("other", { status: status.value }, id);
                }
            });
        }
    };
    // 防抖函数 点击之后500毫秒没有调用该函数则会正常调用,否则重新计时
    const updateDataCommonFunc = useDebounceFn((type: PutRuleTypeParam, data: Record<string, StatusType>, id: number) => {
        esArtPublishRuleApi({ type, data, id }, "put").then(commonThenCallback);
    }, 500);
    // 默认插槽
    const defaultSlot = (str: string) => ({ default: () => str });
    // 操作
    const actionColumn: TableColumnType = {
        title: "操作",
        fixed: "right",
        align: "center",
        width: 300,
        customRender(row: any) {
            // 这个row.value 是一整条数据
            const { id } = row.record;
            // 保存状态的按钮
            const saveStatusButton = h(
                Button,
                {
                    type: "link",
                    style: {
                        padding: "4px 8px",
                        color: "#52c41a"
                    },
                    onClick() {
                        if (!row.record.status) {
                            message.error("先开启规则状态!");
                            return;
                        }
                        const data: Record<string, StatusType> = {};
                        for (const key in AllStatus[id]) {
                            const status = AllStatus[id][key];
                            data[key] = status ? 1 : 0;
                        }
                        updateDataCommonFunc("json_status", data, id);
                    }
                },
                { default: () => "保存状态" }
            );
            // 删除规则按钮
            const deleteRuleButton = h(
                Popconfirm,
                {
                    title: "确认删除吗",
                    okText: "确认",
                    cancelText: "取消",
                    onConfirm() {
                        esArtPublishRuleApi({ id: row.record.id }, "delete")
                            .then((res) => commonThenCallback(res, "delete"))
                            .finally(() => {
                                isReloadRuleList.value = true;
                            });
                    }
                },
                {
                    default: () =>
                        h(
                            Button,
                            {
                                danger: true,
                                type: "link",
                                style: {
                                    padding: "4px 8px"
                                }
                            },
                            defaultSlot("删除")
                        )
                }
            );
            // 修改规则
            const updateRuleButton = h(
                Button,
                {
                    type: "link",
                    style: {
                        color: "#faad14",
                        padding: "4px 8px"
                    },
                    onClick() {
                        currentUpdatePublishRule.value = row.value;
                        publishRuleComponentShow.value = true;
                    }
                },
                defaultSlot("修改")
            );
            const oncePublishArticleButton = h(OncePublishArticleButton, { id: row.record.id });
            // customRender函数 需要返回一个虚拟DOM 这个虚拟DOM接受一些子虚拟DOM
            // 而OncePublishArticleButton 只是一个组件 需要使用h函数渲染该组件成为虚拟DOM
            // 如果是在模板使用 则不需要h函数 因为在模板中会自动调用该组件的渲染函数 如果该组件为函数组件 那么就调用该函数
            // 父节点
            const parentNode = h("div", {}, [saveStatusButton, oncePublishArticleButton, updateRuleButton, deleteRuleButton]);

            return parentNode;
        }
    };
    // 公共的then回调
    const commonThenCallback = (res: any, type = "update") => {
        const s = type === "update" ? "修改" : "删除";
        if (res.data.code === 200) {
            message.success(s + "成功!");
        } else {
            message.error(s + "失败!");
        }
    };
    return {
        columns: [...columns, ...otherStatusColumns(), ruleStatusColumn, actionColumn],
        isReloadData: isReloadRuleList,
        publishRuleComponentShow,
        currentUpdatePublishRule,
        ruleName,
        isShowRuleName
    };
}

// 将status收集
function collectStutas() {
    const statusFields = [
        "es_search",
        "insert_zuhe_img",
        "insert_img",
        "publish_field_data",
        "title_replace",
        "title_insert_kwd",
        "custom_attrs",
        "column_ids",
        "tag_keywords",
        "cms_keywords",
        "head_insert_kwd",
        "center_insert_kwd",
        "footer_insert_kwd",
        "cms_keywrods",
        "tag_keywrods",
        "content_replace"
    ];

    function collect(obj: any, key: string, id: number) {
        if (Reflect.has(obj, "status")) {
            // 存储到变量中
            AllStatus[id] || (AllStatus[id] = {});
            obj["status"] = !!obj["status"];
            AllStatus[id][key] = toRef(obj, "status");
        }
        return obj;
    }
    return {
        statusFields,
        collect
    };
}

export async function useForamtRuleListTableData(data: any) {
    const $store = ruleStore();

    type ReplaceRule = {
        rule_type: "rule_type_name";
        publish_type: "publish_type_name";
        wyc: "wyc_name";
        create_id: "create_name";
        custom_identifier: "custom_identifier_name";
    };
    const replaceRule: ReplaceRule = {
        rule_type: "rule_type_name",
        publish_type: "publish_type_name",
        wyc: "wyc_name",
        create_id: "create_name",
        custom_identifier: "custom_identifier_name"
    };
    type DataItem = Record<keyof ReplaceRule, unknown>;
    const { options } = toRefs($store);
    await $store.init();
    const { collect, statusFields } = collectStutas();
    // 循环旧的data
    const newDate: Array<TableDataItme> = data.map((obj: DataItem) => {
        const newObj: Partial<TableDataItme> = {};
        let key: keyof DataItem;
        for (key in obj) {
            // 如果包含该字段,则收集状态 status
            if (statusFields.includes(key)) {
                // @ts-ignore 传递id和key
                obj[key] = collect(obj[key], key, obj.id);
            }
            if (replaceRule[key]) {
                // @ts-ignore
                const item: SelectOptionItem = options.value[replaceRule[key]].find((item) => item.value === obj[key]) || {
                    label: "暂无"
                };
                newObj[replaceRule[key]] = item.label;
            }
        }
        return { ...newObj, ...obj };
    });
    return newDate;
}

export type { TableDataItme };
